<template>
  <t-dialog
    v-model:visible="show"
    :width="900"
    :header="plugin.t('pull.title')"
    destroyOnClose
    :closeOnOverlayClick="false"
  >
    <template #body>
      <div class="plugin-miravia-order-pull">
        <t-alert class="alert" theme="info">
          <span v-for="alert in plugin.tm('pull.alert')">{{ alert }}</span>
        </t-alert>
        <t-form label-align="left">
          <t-form-item :label="plugin.t('pull.time')">
            <t-date-picker 
              v-model="form.time" 
              :format="app.time.formatTime()" 
              valueType="Date"
              enable-time-picker
            />
          </t-form-item>
          <t-form-item :label="plugin.t('pull.status')">
            <t-checkbox-group v-model="form.status">
              <t-checkbox v-for="(item, index) in plugin.tm('order.status_text')" :value="index" :key="index">{{ item }}</t-checkbox>
            </t-checkbox-group>
          </t-form-item>
        </t-form>
      </div>
    </template>
    <template #footer>
      <t-button theme="primary" v-if="!loading" @click="onSubmit">
        {{ plugin.t('pull.button') }}
      </t-button>
      <t-progress theme="plump" :percentage="progress" status="active" v-else />
    </template>
  </t-dialog>
</template>
<script setup>
  import { ref, reactive } from 'vue'
  import app from '@/app'
  import index from '../../index'
  import { pull, post } from '@/api/provider/miravia_order'
  import orderStore from '../../store/order'

  const plugin = index.plugin

  const show = ref(false)
  const loading = ref(false)
  const progress = ref(0)
  const form = reactive({
    time: new Date,
    status: Object.keys(plugin.tm('order.status_text'))
  })

  const open = () => {
    show.value = true
    const list = orderStore.getList()
    if(list.length > 0) {
      form.time = list[0].created_time.toDate()
    }
  }

  const onSubmit = async () => {
    loading.value = true
    
    try{
      await onPull(app.time.load(form.time).iso(), form.status)
      app.message('success', plugin.message('pull.message.ok'))
    } catch(e) {
      console.error(e)
      app.message('warning', plugin.message('pull.message.error'))
    }

    await orderStore.reset(1)
    loading.value = false
  }

  // 拉取订单
  const onPull = async (time, status) => {
    const data = {
      time,
      page: 0,
      page_size: 100,
      count: 0
    }
    while(true) {
      const res = await pull(data)
      const total = Math.min(res.countTotal, 5000)

      // 循环订单
      for (let i = 0; i < res.orders.length; i++) {
        await onCreate(res.orders[i], status)
        data.count++
        progress.value = parseInt(data.count / total * 100)
      }
      
      // 准备下次
      if(data.count >= total) return
      // 分页++
      data.page++
    }
  }

  // 创建订单
  const onCreate = async (data, status) => {
    // 过滤状态
    if(status.includes(data.statuses[0])) {
      // 并且状态是已支付的
      if(data.payment_method) {
        await post({
          status: data.statuses[0],
          number: data.order_id,
          name: data.customer_first_name ? data.customer_first_name : 'User',
          count: data.items_count,
          price: data.price,
          voucher: data.voucher_seller,
          created_time: app.time.raw(data.created_at).unix()
        })
      }
    }
  }

  defineExpose({ open })
</script>
<style lang="scss">
  @import '@/style/global';

  .plugin-miravia-order-pull{
    overflow: hidden;

    .alert{
      margin-bottom: 25px;
      span{
        display: block;
        line-height: 25px;
      }
    }
  }
</style>